<template>
    <div class="content-wrapper">
        <el-row class="content-row">
            <el-col class="height-init" :span="24">
                <div class="container">
                    <el-row class="handle-box">
                        <el-input v-model="query.name" placeholder="角色名称" class="handle-input mr10"></el-input>
                        <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
                        <el-button type="primary" icon="el-icon-plus" v-if="checkAuth(auths.add)" class="handle-del" @click="addRole">新增</el-button>
                        <el-button type="primary" icon="el-icon-edit" v-if="checkAuth(auths.update)" class="handle-del" @click="handleEdit">编辑</el-button>
                        <el-button type="primary" icon="el-icon-delete" v-if="checkAuth(auths.delete)" class="handle-del" @click="handleDelete">删除</el-button>
                    </el-row>
                    <el-row class="list-table-row">
                        <el-table
                                :data="tableData"
                                border
                                class="table"
                                height="100%"
                                ref="multipleTable"
                                header-cell-class-name="table-header"
                                @selection-change="handleSelectionChange"
                        >
                            <el-table-column type="selection" width="55" align="center"></el-table-column>
                            <el-table-column type="index" align="center" width="50" label="序号" />
                            <el-table-column prop="name" align="center" label="角色名称"></el-table-column>
                            <el-table-column prop="description" align="center" label="角色描述" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="createUser" align="center" label="创建人"></el-table-column>
                            <el-table-column prop="createTime" align="center" label="创建时间" show-overflow-tooltip>
                                <template slot-scope="scope" >
                                    {{renderTime(scope.row.createTime)}}
                                </template>
                            </el-table-column>
                            <el-table-column prop="updateTime" align="center" label="修改时间" show-overflow-tooltip>
                                <template slot-scope="scope" >
                                    {{renderTime(scope.row.updateTime)}}
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-row>
                    <el-row class="pagination-self">
                        <el-pagination
                                background
                                layout="total, sizes, prev, pager, next"
                                :current-page="query.pageNo"
                                :page-size="query.pageSize"
                                :total="pageTotal"
                                @size-change="handleSizeChange"
                                @current-change="handlePageChange"
                        ></el-pagination>
                    </el-row>
                </div>
            </el-col>
        </el-row>

        <!-- 新增弹出框 -->
        <el-dialog title="新增角色" :visible.sync="addVisible" width="52%" v-loading.fullscreen.lock="fullscreenLoading">
            <el-form ref="addForm" :model="addForm" :rules="addRules" label-width="80px">
                <el-row style="height: 350px">
                    <el-col :span="12">
                        <el-form-item label="角色名称" prop="name">
                            <el-input v-model="addForm.name"></el-input>
                        </el-form-item>
                        <el-form-item label="创建时间" prop="createTime">
                            <el-input v-model="addForm.createTime" readonly></el-input>
                        </el-form-item>
                        <el-form-item label="创建人" prop="createUser">
                            <el-input v-model="addForm.createUser" readonly></el-input>
                        </el-form-item>
                        <el-form-item label="角色描述" prop="description">
                            <el-input type="textarea" rows="6" v-model="addForm.description"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" style="height:100%;overflow-y: scroll">
                        <el-form-item prop="menus">
                            <el-tree
                                    :data="menuTreeData"
                                    :props="menuProps"
                                    node-key="id"
                                    ref="addMenuTree"
                                    @check-change="getAddFormMenuIds"
                                    show-checkbox
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveRole('addForm')">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑角色" :visible.sync="editVisible" width="52%" v-loading.fullscreen.lock="fullscreenLoading">
            <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="80px">
                <el-row style="height: 350px">
                    <el-col :span="12">
                        <el-form-item label="角色名称" prop="name">
                            <el-input v-model="editForm.name"></el-input>
                        </el-form-item>
                        <el-form-item label="创建时间" prop="createTime">
                            <el-input v-model="editForm.createTime" readonly></el-input>
                        </el-form-item>
                        <el-form-item label="创建人" prop="createUser">
                            <el-input v-model="editForm.createUser" readonly></el-input>
                        </el-form-item>
                        <el-form-item label="角色描述" prop="description">
                            <el-input type="textarea" rows="6" v-model="editForm.description"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" style="height:100%;overflow-y: scroll">
                        <el-form-item prop="menus">
                            <el-tree
                                    :data="menuTreeData"
                                    :props="menuProps"
                                    node-key="id"
                                    ref="editMenuTree"
                                    @check-change="getEditFormMenuIds"
                                    show-checkbox
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateRole('editForm')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import bus from '@/components/common/bus';
import { fetchList, saveRole, menuPermission, updateRole, deleteRole } from '../../../../api/sys/role'
import { getMenus } from '../../../../api/sys/user'
import { renderTime,renderTimeWithOutYear,renderTimeNoTime } from '../../../../common/js/vue-mixin'

export default {
    name: 'roleList',
    data() {
        return {
            query: {
                name: '',
                pageNo: 1,
                pageSize: 20
            },
            tableData: [],
            multipleSelection: [],
            delList: [],
            addVisible:false,
            editVisible: false,
            pageTotal: 0,
            fullscreenLoading: false,
            addForm:{
                name:'',
                description:'',
                createUser:JSON.parse(localStorage.getItem("user")).name,
                createTime:this.renderTime(new Date().getTime()),
                menus:[],
            },
            editForm: {
                name:'',
                description:'',
                createUser:'',
                createTime:'',
                menus:[],
            },
            menuTreeData:[],
            menuProps: {
                children: 'children',
                label: 'name',
                isLeaf: 'leaf'
            },
            addRules: {
                name: [
                    { required: true, message: '请输入角色名称', trigger: ['blur','change'] }
                ],
                description:[
                    { required: true, message: '请输入角色描述', trigger: ['blur','change'] }
                ],
                menus:[
                    { required: true, message: '请选择菜单', trigger: ['blur','change'] }
                ]
            },
            editRules: {
                name: [
                    { required: true, message: '请输入角色名称', trigger: ['blur','change'] }
                ],
                description:[
                    { required: true, message: '请输入角色描述', trigger: ['blur','change'] }
                ],
                menus:[
                    { required: true, message: '请选择菜单', trigger: ['blur','change'] }
                ]
            }
        };
    },
    created() {
        this.getMenu();
        this.getData();
    },
    props:['auths'],
    methods: {
        //选择树节点 触发获取树节点数据
        getAddFormMenuIds(){
            this.addForm.menus = [];
            let treeDataList = this.$refs.addMenuTree.getCheckedNodes();
            treeDataList.forEach(node=>{
                this.addForm.menus.push(node.id);
            });
            let halfTreeDataList = this.$refs.addMenuTree.getHalfCheckedNodes();
            halfTreeDataList.forEach(node=>{
                this.addForm.menus.push(node.id);
            });
            console.log(this.addForm.menus);
        },
        //保存用户信息
        saveRole(formName){
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.fullscreenLoading=true;
                    this.addForm.createTime = new Date().getTime();
                    saveRole(this.addForm).then(res => {
                        console.log(res);
                        if (res.code == '0') {
                            this.$refs.addMenuTree.setCheckedKeys([]);
                            this.fullscreenLoading=false;
                            this.addVisible = false;
                            this.$message({
                                message: '新增成功',
                                type: 'success'
                            });
                            this.resetForm('addForm');
                            this.addForm.menus = [];
                            this.getData();
                        } else {
                            this.fullscreenLoading=false;
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //获取菜单信息
        getMenu(){
            getMenus({needButton:1}).then(res => {
                this.menuTreeData = res.data;
            });
        },
        /**
         * 获取列表数据
         */
        getData() {
            fetchList(this.query).then(res => {
                console.log(res);
                this.tableData = res.data.records;
                this.pageTotal = res.data.total || 50;
            });
        },
        //新增角色
        addRole(){
            let that = this;
            this.resetForm('addForm');
            this.addForm.menus = [];
            this.addVisible = true;
            setTimeout(function () {
                that.$refs.addMenuTree.setCheckedKeys([]);
            },100)
        },
        //触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageNo', 1);
            this.getData();
        },
        // 删除操作
        handleDelete() {
            if(this.multipleSelection.length>0){
                    // 二次确认删除
                let selIds = this.multipleSelection.map((item,index)=>{return item.id});
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    deleteRole({ids:selIds}).then(res => {
                        if (res.code == '0') {
                            this.$message.success('删除成功');
                            this.getData();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    });
                }).catch(() => {

                });
            }else{
                this.$message({
                    message: '请选择记录!',
                    type: 'error'
                });
            }

        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        // 编辑操作
        handleEdit() {
            if(this.multipleSelection.length>0){
                if(this.multipleSelection.length==1){
                    let row = this.multipleSelection[0];
                    Object.assign(this.editForm,row);
                    this.editForm.createTime = this.renderTime(row.createTime);
                    this.editVisible = true;
                    menuPermission({id:row.id}).then(res => {
                        if (res.code == '0') {
                            let data = res.data;
                            this.$refs.editMenuTree.setCheckedKeys([]);
                            this.editForm.menus=[];
                            data.forEach((value)=>{
                                this.editForm.menus.push(value.menuId);
                                this.$refs.editMenuTree.setChecked(value.menuId,true,false);
                            })
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    });
                }else{
                    this.$message({
                        message: '只能选择一条记录进行编辑!!',
                        type: 'error'
                    });
                }
            }else{
                this.$message({
                    message: '请选择记录!',
                    type: 'error'
                });
            }
        },
        //编辑获取树的时候处理
        getEditFormMenuIds(){
            this.editForm.menus=[];
            let treeDataList = this.$refs.editMenuTree.getCheckedNodes();
            treeDataList.forEach(node=>{
                this.editForm.menus.push(node.id);
            });
            let halfTreeDataList = this.$refs.editMenuTree.getHalfCheckedNodes();
            halfTreeDataList.forEach(node=>{
                this.editForm.menus.push(node.id);
            });
        },
        // 编辑保存
        updateRole(formName) {
            console.log(this.editForm);
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.fullscreenLoading=true;
                    updateRole(this.editForm).then(res => {
                        console.log(res);
                        if (res.code == '0') {
                            this.$refs.editMenuTree.setCheckedKeys([]);
                            this.fullscreenLoading=false;
                            this.editVisible = false;
                            this.$message({
                                message: '更新成功',
                                type: 'success'
                            });
                            this.resetForm('editForm');
                            this.editForm.menus = [];
                            this.getData();
                        } else {
                            this.fullscreenLoading=false;
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageNo', val);
            this.getData();
        },
        //分页码数修改
        handleSizeChange(val) {
            this.$set(this.query, 'pageSize', val);
            this.getData();
        },
    }
};
</script>
<style>
    .el-tree{
    }
    .el-checkbox:last-of-type{
        margin-right: 6px;
    }
</style>

<style scoped>

    .content-wrapper{
        height:100%;
        overflow-y: hidden;
    }

    .content-row{
        height: 100%;
    }

    .height-init{
        height: 100%;
    }

    .container{
        height: 100%;
    }

    .handle-box {
        height: 6.5%;
    }

    .handle-input {
        width: 120px;
        display: inline-block;
    }

    .list-table-row{
        height:83%;
    }

    .table {
        width: 100%;
        height: 100%;
        font-size: 14px;
    }
    .red {
        color: #ff0000;
    }
    .mr10 {
        margin-right: 10px;
    }
    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }
    .pagination-self{
        height:10%;
        text-align: right;
        margin-top: 5px;
    }
</style>
